//
//  Util.m
//  vm
//
//  Created by 孔祥 on 14-9-27.
//  Copyright (c) 2014年 孔祥. All rights reserved.
//

#import "Util.h"

@implementation Util

+ (BOOL) isBlankString:(NSString *)string {
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    return NO;
}

+ (UIColor*) uiColorFromHexString:(NSString *)hexstr {
    
    NSScanner* scan = [NSScanner scannerWithString:[hexstr substringWithRange:NSMakeRange(1, 2)]];
    unsigned int red = 0;
    [scan scanHexInt:&red]; //NSLog(@"###%d", red);
    
    scan = [NSScanner scannerWithString:[hexstr substringWithRange:NSMakeRange(3, 2)]];
    unsigned int green = 0;
    [scan scanHexInt:&green]; //NSLog(@"###%d", green);
    
    scan = [NSScanner scannerWithString:[hexstr substringWithRange:NSMakeRange(5, 2)]];
    unsigned int blue = 0;
    [scan scanHexInt:&blue]; //NSLog(@"###%d", blue);
    
    
    UIColor* color= [UIColor colorWithRed:((float)red)/255.0 green:((float)green)/255.0 blue:((float)blue)/255.0 alpha:1] ;
    
    return color;
}

+(int) gmt
{

    NSDate *nsnow=[NSDate date];
    
    return (int)[self toGMTFromNSDate:nsnow];
}
////界面上的时间存入数据库时用（全球单一时钟）
//+(NSInteger) dbTimeStamp1970:(NSString*)sDate
//{
//    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
//    [formatter setDateFormat:@"yyyy-MM-dd"];
//    NSDate *_时区Day=[formatter dateFromString:@"1970-01-01"];
//    //NSLog(@"_时区Day=%@", _时区Day);
//    NSInteger _补偿秒数=-[_时区Day timeIntervalSince1970];
//    
//    
//    NSInteger _时区秒数=[[formatter dateFromString:sDate] timeIntervalSince1970];
//    return _时区秒数+_补偿秒数;
//}
+(NSInteger) toGMTFromNSDate:(NSDate*)nsDate
{
    /*
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *_时区Day=[formatter dateFromString:@"1970-01-01"];
    //NSLog(@"_时区Day=%@", _时区Day);
    NSInteger _补偿秒数=-[_时区Day timeIntervalSince1970];
    
    
    NSInteger _时区秒数=[nsDate timeIntervalSince1970];
    return _时区秒数+_补偿秒数;
     */
    NSTimeZone* destinationTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];//或GMT
    NSTimeZone* sourceTimeZone = [NSTimeZone localTimeZone];
    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:nsDate];
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:nsDate];
    NSInteger destinationSeconds=[nsDate timeIntervalSince1970];
    //得到时间偏移量的差值
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
    
    return interval+destinationSeconds;
}

//当需要把来自数据库的时间显示到界面上 才用
+(NSDate*) toNSDateFromGMT:(long)dbLong
{
    NSDate* nsDate = [[NSDate alloc] initWithTimeIntervalSince1970:dbLong];
    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];//或GMT
    NSTimeZone* destinationTimeZone = [NSTimeZone localTimeZone];
    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:nsDate];
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:nsDate];
    //得到时间偏移量的差值
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
    
    NSDate* destinationDateNow = [[NSDate alloc] initWithTimeInterval:interval sinceDate:nsDate];
    //NSDate *uiNeedDate=[NSDate dateWithTimeIntervalSince1970:timeIntervalSince1970];
    
    return destinationDateNow;
}

+(NSDate*) toNSDateFromString:(NSString*)uiDate
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateFormat:@"yyyy-MM-dd"];
    
    return [formatter dateFromString:uiDate];
}

+(NSDate*) toZeroHourDate:(NSDate*)nsDate
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateFormat:@"yyyy-MM-dd"];

    NSString *sDate=[formatter stringFromDate:nsDate];
    NSDate *date=[formatter dateFromString:sDate];
    return date;
}

+(NSDate*) zeroHourDate:(long)longDate
{
    NSInteger r=longDate%86400;
    
    return [[NSDate alloc] initWithTimeIntervalSince1970:(longDate-r)];

}


//输入的日期字符串形如：@"1992-05-21 13:08:08"
//
//- (NSDate *)dateFromString:(NSString *)dateString{
//    NSDateFormatter *dateFormatter = [[NSDateFormatteralloc] init];
//    [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];

//--------------------------------------------------------------------------------------------------
+ (NSMutableDictionary *) dictWithNsnullKVs:(NSArray *)firstObject, ... NS_REQUIRES_NIL_TERMINATION
{
    va_list varList;
    NSArray* pare;
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    if(firstObject){
        if(firstObject.count==1)
            [dict setValue:[NSNull null] forKey:firstObject[0]];
        else
            [dict setValue:firstObject[1] forKey:firstObject[0]];
        
        va_start(varList, firstObject);
        while((pare = va_arg(varList, NSArray*))){
            if(pare.count==1)
                [dict setValue:[NSNull null] forKey:pare[0]];
            else
                [dict setValue:pare[1] forKey:pare[0]];
        }
        va_end(varList);
    }
    
    return dict;
}


//--------------------------------------------------------------------------------------------------
+ (NSString * ) createDirIfNotExist:(NSString *)relPath
{
    NSString * documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString * absolutePath = [documentDirectory stringByAppendingPathComponent:relPath];
    //NSLog(@"absolutePath =%@", absolutePath);
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL exist = [fileManager  fileExistsAtPath:absolutePath]; //Returns a Boolean value that indicates whether a file or directory exists at a specified path.
    
    NSError *err=[NSError new];
    if (!exist) {
        BOOL succ=[fileManager createDirectoryAtPath:absolutePath withIntermediateDirectories:YES attributes:nil  error:&err];
        if (!succ){
            NSLog(@"creat fail %ld, reason:%@", (long)[err code], [err description]);
            return nil;
        }
    }
    
    //[UIImageJPEGRepresentation(image, 1.0) writeToFile:jpgPath atomically:YES];
    
    return [absolutePath stringByAppendingString:@"/"];
}


+ (BOOL) delFileIfExist:(NSString *)relPath
{
    NSString * documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString * absolutePath = [documentDirectory stringByAppendingPathComponent:relPath];
    //NSLog(@"delPath =%@", absolutePath);
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL exist = [fileManager  fileExistsAtPath:absolutePath]; //Returns a Boolean value that indicates whether a file or directory exists at a specified path.
    
    NSError *err=[NSError new];
    if (exist) {
        BOOL succ=[fileManager removeItemAtPath:absolutePath  error:&err];
                   //de attributes:nil  error:&err];
        if (!succ){
            NSLog(@"del fail %ld, reason:%@", (long)[err code], [err description]);
            return false;
        }
    }

    return true;
}

+ (BOOL) rename:(NSString *)relPath  fromName:(NSString *)fromPath   toName:(NSString *)toPath
{
    NSString * documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString * absoluteDir = [documentDirectory stringByAppendingPathComponent:relPath];
    NSLog(@"absoluteDir =%@", absoluteDir);
    
    NSString * srcPath = [absoluteDir stringByAppendingPathComponent:fromPath];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL exist = [fileManager  fileExistsAtPath:srcPath]; //Returns a Boolean value that indicates whether a file or directory exists at a specified path.
    
    NSError *err=[NSError new];
    if (exist) {
        NSString * destPath = [absoluteDir stringByAppendingPathComponent:toPath];
        BOOL succ=[fileManager moveItemAtPath:srcPath toPath:destPath error:&err];
        if (!succ){
            NSLog(@"rename fail %ld, reason:%@", (long)[err code], [err description]);
            return false;
        }
    }
    
    return true;
}

+ (NSString *) getABSpath:(NSString *)relPath  fileName:(NSString *)fromPath
{
    NSString * documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString * absoluteDir = [documentDirectory stringByAppendingPathComponent:relPath];
    NSLog(@"absoluteDir =%@", absoluteDir);
    
    NSString * srcPath = [absoluteDir stringByAppendingPathComponent:fromPath];
    
    return srcPath;
}

//----------------------------------------------------------------------
+ (BOOL) judgeFileIfExist:(NSString *)filename relPath:(NSString *)relPath
{
    NSString * documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString * absolutePath = [documentDirectory stringByAppendingPathComponent:relPath];
    //NSLog(@"judgeFileIfExist =%@", absolutePath);
    
    NSString * srcPath = [absolutePath stringByAppendingPathComponent:filename];
    //NSLog(@"judgeFileIfExist srcPath=%@", srcPath);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    return [fileManager  fileExistsAtPath:srcPath]; //Returns a Boolean value that indicates whether a file or directory exists at a specified path.
}

//----------------------------------------------------------------------

+ (NSNumber *) toNSNumber:(id)val
{
    if (val==nil) {
        return [NSNumber numberWithInteger:0];
    }
    if ([val isKindOfClass:[NSNumber class]]) {
        return val;
    }
    
    if ([val isKindOfClass:[NSString class]]) {
        return [NSNumber numberWithInteger:[val integerValue]];
    }
    
    return nil;
}

+ (NSNumber *) toNSDateNumber:(id)val
{
    if ([val isKindOfClass:[NSNumber class]]) {
        return val;
    }
    
    if ([val isKindOfClass:[NSString class]]) {
        //"endDate":"1417759936000"
        if ([val length]==13) {
            val=[val substringToIndex:10];
        }
        return [NSNumber numberWithInteger:[val integerValue]];
    }
    
    return nil;
}
+ (int) toInt:(id)val
{
    if ([val isKindOfClass:[NSNumber class]]) {
        return [val intValue];
    }
    
    if ([val isKindOfClass:[NSString class]]) {
        //"endDate":"1417759936000"
        if ([val length]==13) {
            val=[val substringToIndex:10];
        }
        return [val intValue];
    }
    
    return 0;
}
+ (long) toLong:(id)val
{
    if ([val isKindOfClass:[NSNumber class]]) {
        return [val longValue];
    }
    
    if ([val isKindOfClass:[NSString class]]) {
        return (long)[val longLongValue];
    }
    
    return 0;
}

+ (void)showMessageAlert:(NSString *)message
{
    if([message length]) {
        //处理前台消息框弹出
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Notification",@"Notification") message:message delegate:self cancelButtonTitle:NSLocalizedString(@"OK", @"OK") otherButtonTitles:nil];
        [alert show];
    }
    else
    {
        NSLog(@"showMessageAlert: Message is nil...[%@]",message);
    }
    
}


+ (int)getRandomNumber:(int)from to:(int)to
{
    return (int)(from + (arc4random() % (to - from + 1))); //+1,result is [from to]; else is [from, to)!!!!!!!
}


+ (NSArray *)splitToInts:(NSString *)str
{
    NSMutableArray *ints=[NSMutableArray new];
    str =[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSArray *compStrs= [str componentsSeparatedByString:@","];
    for (NSString *str in compStrs) {
        if (str==nil || [str isEqualToString:@""]) {
            continue;
        }
        long lval=[str integerValue];
        [ints addObject:[NSNumber numberWithLong:lval]];
    }
    return ints;
}

+(BOOL) startWith:(NSString*)prefix forString:(NSString*)text
{
    if ( text != nil && prefix != nil ){
        if ( [prefix length] > [text length] ) {
            return NO;
        }
        NSString* prestr = [text substringToIndex:[prefix length]];
        return [prestr isEqualToString:prefix];
    }
    return NO;
}

+(BOOL) endWith:(NSString*)suffix forString:(NSString*)text
{
    if ( text != nil && suffix != nil ){
        if ( [suffix length] > [text length] ) {
            return NO;
        }
        NSInteger len = [text length] - [suffix length];
        NSString* sufstr = [text substringFromIndex:len];
        return [sufstr isEqualToString:suffix];
    }
    return NO;
}

+(NSMutableDictionary*) getRefreshDict:(NSString*)name
{
    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *settingPlistPath = [pathArray objectAtIndex:0];
    NSString *settingPlist=[settingPlistPath stringByAppendingPathComponent:name];
    NSMutableDictionary* settingDict =  [[NSMutableDictionary alloc ] initWithContentsOfFile:settingPlist];
    
    return settingDict;
}

+(void) setRefreshDict:(NSString*)name dict:(NSDictionary*)dict
{
    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *settingPlistPath = [pathArray objectAtIndex:0];
    NSString *settingPlist=[settingPlistPath stringByAppendingPathComponent:name];
    
    [dict writeToFile:settingPlist atomically:YES];
}


+(NSDate *)toNSDateFromRfc3339String:(NSString *)rfc3339DateTimeString
{
    NSDateFormatter *rfc3339DateFormatter = [[NSDateFormatter alloc] init];
    NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
    
    [rfc3339DateFormatter setLocale:enUSPOSIXLocale];
    //[rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
    [rfc3339DateFormatter setDateFormat:@"yyyyMMdd'T'HHmmss"];
    NSTimeZone *timeZone=[NSTimeZone systemTimeZone];
    [rfc3339DateFormatter setTimeZone:timeZone];  //?[NSTimeZone timeZoneForSecondsFromGMT:0]
    
    // Convert the RFC 3339 date time string to an NSDate.
    NSDate *date = [rfc3339DateFormatter dateFromString:rfc3339DateTimeString];
    
    return date;
}

+(NSString *)toRfc3339DateTimeString:(NSDate *)date
{
    NSDateFormatter *rfc3339DateFormatter = [[NSDateFormatter alloc] init];
    NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
    
    [rfc3339DateFormatter setLocale:enUSPOSIXLocale];
    //[rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
    [rfc3339DateFormatter setDateFormat:@"yyyyMMdd'T'HHmmss"];
    NSTimeZone *timeZone=[NSTimeZone systemTimeZone];
    [rfc3339DateFormatter setTimeZone:timeZone];  //?[NSTimeZone timeZoneForSecondsFromGMT:0]
    
    
    NSString *string = [rfc3339DateFormatter stringFromDate:date];
    
    return string;
}


+(NSMutableArray *)sortArray:(NSArray *)array  fieldName:(NSString *)fldkey  ascending:(BOOL)ascending
{
    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:fldkey ascending:ascending];
    NSMutableArray *newarray = [NSMutableArray arrayWithArray:[array sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]]];
    
    return newarray;
}

//[Util filterDictionary:[pushObj toDictionary] from:@"Id" to:@"id"]
+(NSDictionary *)filterDictionary:(NSDictionary *)dict from:(NSString *)from to:(NSString *)to
{
    if (!dict) {
        return nil;
    }
    
    id val=[dict objectForKey:from];
    if (!val) {
        return dict;
    }
    
    NSMutableDictionary *mDict;
    if (![dict isKindOfClass:[NSMutableDictionary class]] ) {
        mDict=[NSMutableDictionary dictionaryWithDictionary:dict];
    }else{
        mDict=(NSMutableDictionary *)dict;
    }
    
    [mDict removeObjectForKey:from];
    [mDict setValue:val forKey:to];
    return mDict;
}

+(id) getParam:(NSString*)pname fromPlist:(NSString*)fname
{
    NSString * configTablePath = [[NSBundle bundleForClass: [self class]] pathForResource:fname ofType:@"plist"];
    NSDictionary * configTable = [[NSDictionary alloc] initWithContentsOfFile:configTablePath];
//    NSString *FamNotesHost = [configTable objectForKey:@"IP"];
//    int FamNotesPort = 80;
//    NSString *sPort=[configTable objectForKey:@"PORT"];
//    if (sPort) {
//        FamNotesPort = sPort.intValue;
//    }
    if([@"ALL" isEqualToString:pname])
        return configTable;
    
    return [configTable valueForKey:pname];
}


+ (int) indexOf:(NSString *)subStr forString:(NSString *)text{
    NSRange range = [text rangeOfString:subStr];
    if ( range.length > 0 ) {
        return (int)range.location;
    } else {
        return -1;
    }
}

@end
